package com.yphone.ui.yun;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.TrafficStats;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.yphone.net.IUIDataListener;
import com.yphone.net.bean.BaseResultWrapper;
import com.zzkj.yunphone.R;
import com.iiordanov.bVNC.event.bVNCEvent;
import com.yphone.tools.MyLog;
import com.yphone.tools.RemoteUtils;
import com.yphone.ui.login.manager.LoginManager;
import com.yphone.ui.login.view.TelView;
import com.yphone.ui.ysj.bean.RemoteConnectBean;

import org.greenrobot.eventbus.EventBus;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;


public class RemoteDeviceListActivity extends Activity {

    private ListView listview;
    private List<RemoteConnectBean> remoteConnectBeans;
    private int mId;
    private int mPort;
    private boolean exitFlag = true;
    private TextView tv_spend;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        overridePendingTransition(R.anim.int_to_left, R.anim.out_to_left);
        super.onCreate(savedInstanceState);
        super.setTheme(android.R.style.Theme_Translucent_NoTitleBar);
        setContentView(R.layout.activity_list);
        initView();
        initData();

    }

    private void initData() {
        Intent intent = getIntent();
        mId = intent.getIntExtra("id",-1);
        MyLog.e("RemoteDeviceListActivity mId = "+mId);
        remoteConnectBeans = LoginManager.getInstance().getInfo().remoteConnectBeans;

        listview.setAdapter(new BaseAdapter() {
            @Override
            public int getCount() {
                return remoteConnectBeans.size();
            }

            @Override
            public Object getItem(int position) {
                return null;
            }

            @Override
            public long getItemId(int position) {
                return 0;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                //#3391FA
                final RemoteConnectBean remoteConnectBean = remoteConnectBeans.get(position);
                View root = View.inflate(RemoteDeviceListActivity.this, R.layout.item_devices_name, null);
                TextView tv_name = root.findViewById(R.id.tv_name);
                if (!TextUtils.isEmpty(remoteConnectBean.getName())) {
                    tv_name.setText(remoteConnectBean.getName());
                }
                if (remoteConnectBean.id == mId) {
//                    tv_name.setTextColor(Color.parseColor("#3391FA"));
                    root.setBackgroundResource(R.drawable.item_device_list_bg_gradient);
                } else {
                    root.setBackgroundResource(R.color.transparent);
                    root.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            RemoteDeviceListActivity.this.finish();
                            MyLog.e("点击root");

                            RemoteUtils.toRemote(remoteConnectBean.id, new IUIDataListener() {
                                @Override
                                public void uiDataError(Exception exc) {

                                }

                                @Override
                                public void uiDataSuccess(Object obj) {
                                    BaseResultWrapper<RemoteConnectBean> wrapper = (BaseResultWrapper<RemoteConnectBean>) obj;
                                    RemoteConnectBean bean = wrapper.data;
                                    String[] split = bean.ip.split(":");

                                    EventBus.getDefault().post(new bVNCEvent.closeRemoteAndOpen(split[0],Integer.parseInt(split[1]),bean.token,remoteConnectBean.id));
                                }
                            });


//                            RemoteUtils.toRemote(RemoteDeviceListActivity.this, remoteConnectBean);
                        }
                    });
                }

                return root;
            }
        });
    }

    private void initView() {
        listview = findViewById(R.id.listview);
        tv_spend = findViewById(R.id.tv_spend);
        findViewById(R.id.ll_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        findViewById(R.id.ll_root).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        while (exitFlag){
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            final String delay = getDelay();
                            tv_spend.post(new Runnable() {
                                @Override
                                public void run() {
                                    tv_spend.setText(delay+" ms");
                                }
                            });
                        }
                    }
                }
        ).start();
    }

    public String getDelay(){
        String delay ="";
        Process p =null;
        try{
            p = Runtime.getRuntime().exec("/system/bin/ping -c 1 "+"192.168.50.193");
            BufferedReader buf =new BufferedReader(new InputStreamReader(p.getInputStream()));
            String str ="";
            while((str=buf.readLine())!=null){
                MyLog.e("str = "+str);
                if(str.contains("avg")){
                    int i=str.indexOf("/",20);
                    int j=str.indexOf(".", i);
                    MyLog.e("延迟:"+str.substring(i+1, j));
                    delay =str.substring(i+1, j);
                }
            }
        }catch(IOException e) {
            MyLog.e(Log.getStackTraceString(e));
        }
        return delay;

    }

    private long rxtxTotal = 0;

    private DecimalFormat showFloatFormat = new DecimalFormat("0.00");

    public void updateViewData() {
        long tempSum = TrafficStats.getTotalRxBytes()
                + TrafficStats.getTotalTxBytes();
        long rxtxLast = tempSum - rxtxTotal;
        double totalSpeed = rxtxLast * 1000 / 2000d;
        rxtxTotal = tempSum;
        MyLog.e("当前网速:" + showSpeed(totalSpeed)); //设置显示当前网速

    }


    private String showSpeed(double speed) {
        String speedString;
        if (speed >= 1048576d) {
            speedString = showFloatFormat.format(speed / 1048576d) + "MB/s";
        } else {
            speedString = showFloatFormat.format(speed / 1024d) + "KB/s";
        }
        return speedString;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        exitFlag = false;
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.int_to_left, R.anim.out_to_left);
    }
}
